import axios from 'axios'
import { message } from 'ant-design-vue'
import router from '@/router'
import { useUserStore } from '@/stores/user'

const request = axios.create({
  baseURL: 'http://localhost:8123/api/', // Replace with your API base URL
  timeout: 5000, // Request timeout in milliseconds
  headers: {
    'Content-Type': 'application/json',
  },
})

// Request interceptor
request.interceptors.request.use(
  (config) => {
    // Add authorization token or other custom logic before request is sent
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Auth = token
    }
    return config
  },
  (error) => {
    // Handle request error
    message.error('请求发送失败')
    return Promise.reject(error)
  },
)

// Response interceptor
request.interceptors.response.use(
  (response) => {
    // Process the response data
    const res = response.data
    
    // 根据后端的响应格式进行处理
    if (res.code === 0) {
      // 请求成功
      return res.data
    } else {
      // 请求失败但有响应
      message.error(res.message || '请求失败')
      
      // 处理特定错误码
      if (res.code === 40100 || res.code === 40101) {
        // 40100: 未登录, 40101: 无权限
        const userStore = useUserStore()
        userStore.logout()
        
        // 如果不在登录页，则跳转到登录页
        if (router.currentRoute.value.path !== '/login') {
          message.warning('请先登录')
          router.push({
            path: '/login',
            query: { redirect: router.currentRoute.value.fullPath }
          })
        }
      }
      
      return Promise.reject(new Error(res.message || '请求失败'))
    }
  },
  (error) => {
    // Handle response errors
    if (error.response) {
      // Server responded with a status other than 2xx
      const status = error.response.status
      
      // 根据HTTP状态码显示不同的错误消息
      switch (status) {
        case 401:
          message.error('未授权，请重新登录')
          // 清除用户状态并跳转到登录页
          const userStore = useUserStore()
          userStore.logout()
          router.push('/login')
          break
        case 403:
          message.error('拒绝访问')
          break
        case 404:
          message.error('请求的资源不存在')
          break
        case 500:
          message.error('服务器错误')
          break
        default:
          message.error('请求失败')
      }
      
      console.error('响应错误:', status, error.response.data)
    } else if (error.request) {
      // Request was made but no response received
      message.error('网络错误，请检查您的网络连接')
      console.error('未收到响应:', error.request)
    } else {
      // Something else caused the error
      message.error('请求错误: ' + error.message)
      console.error('错误:', error.message)
    }
    return Promise.reject(error)
  },
)

export default request
